package com.chen.im.view;

import com.chen.common.FX;
import com.chen.boot.db.entity.ChatMessage;

import java.io.IOException;

import javafx.application.Platform;
import javafx.collections.FXCollections;
import javafx.collections.ObservableList;
import javafx.fxml.FXML;
import javafx.fxml.FXMLLoader;
import javafx.scene.control.ListCell;
import javafx.scene.control.ListView;
import javafx.scene.layout.HBox;
import lombok.SneakyThrows;

/**
 * @Description
 * @Author Pengwei
 * @CreatDate 2021/11/14 14:18
 */
public class ChatList {
    @FXML
    ListView<String> chatListView;
    public static ObservableList<String> items = FXCollections.observableArrayList();

    @FXML
    public void initialize() {
        chatListView.setItems(items);
        //设置聊天的自定义组件
        setMsgListView();
    }

    //设置聊天的自定义组件
    private void setMsgListView() {
        chatListView.setCellFactory(param -> new ListCell<String>() {
            @SneakyThrows
            @Override
            protected void updateItem(String item, boolean empty) {
                Platform.runLater(() -> {
                    try {
                        super.updateItem(item, empty);
                        //如果数据为空,setGraphic(null),避免重复数据
                        if (empty || item == null) {
                            setGraphic(null); return;
                        }
                        FXMLLoader msgPage = FX.getFXMLLoader("/view/ChatList_item_obj.fxml");
                        HBox hBox = msgPage.load();
                        hBox.setPrefWidth(0);//重要,不设置此项item会超出屏幕,形成滑动bar
                        this.setGraphic(hBox);
                        ChatListItem chatListItem = msgPage.getController();
                        chatListItem.setData(item);
                    } catch (IOException e) {
                        setGraphic(null);
                        e.printStackTrace();
                    }
                });
            }
        });
    }
}
